﻿/**
* CRL
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace CRL.LambdaQuery
{
    public sealed partial class LambdaQueryResultSelect<TResult>
    {
        public async Task<List<TResult>> ToListAsync()
        {
            if (resultSelectorBody is MemberInitExpression)
            {
                var memberInitExp = (resultSelectorBody as MemberInitExpression);
                resultSelectorBody = memberInitExp.NewExpression;
            }
            var db = DBExtendFactory.CreateDBExtend(BaseQuery.__DbContext);

            if (resultSelectorBody is NewExpression)
            {
                var newExpression = resultSelectorBody as NewExpression;
                return await db.QueryResultAsync<TResult>(BaseQuery, newExpression);
            }
            else if (resultSelectorBody is MemberExpression)
            {
                var result = await db.QueryDynamicAsync(BaseQuery);
                var mExp = resultSelectorBody as MemberExpression;
                var list = new List<TResult>();
                foreach (var item in result)
                {
                    var dic = item as IDictionary<string, object>;
                    var obj = dic[mExp.Member.Name];
                    list.Add((TResult)obj);
                }
                return list;
            }
            else if (resultSelectorBody is ParameterExpression)
            {
                return await db.QueryResultAsync<TResult>(BaseQuery);
            }

            throw new Exception("ToList不支持此表达式 " + resultSelectorBody);
        }

        public Task<List<TResult2>> ToListAsync<TResult2>()
        {
            var db = DBExtendFactory.CreateDBExtend(BaseQuery.__DbContext);
            return db.QueryResultAsync<TResult2>(BaseQuery);
        }
    }
}
